package com.jgp.control;

import com.jgp.Exception.BusinessException;
import com.jgp.Exception.SystemException;
import com.jgp.domain.Book;
import com.jgp.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag =bookService.save(book);
        return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
    @PutMapping
    public Result updata(@RequestBody Book book) {
        boolean flag =bookService.updata(book);
        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,flag);

    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag =bookService.delete(id);
        return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag);
    }


    @GetMapping("/{id}")
    public Result getbyid(@PathVariable Integer id) {
        if (id>=100){
            throw new BusinessException(Code.BUSINESS_ERR,"请输入正确的id");
        }

       Book book= bookService.getbyid(id);
       Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
       String msg= book!=null?"":"数据查询失败请重试";
        return new Result(code,book,msg);

    }
    @GetMapping
    public Result getall() {
        List<Book> book= bookService.getall();
        Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
        String msg= book!=null?"":"数据查询失败请重试";
        return new Result(code,book,msg);

    }
}
